package logic

import (
	"encoding/json"
	"log"
	"mssgserver/constant"
	"mssgserver/db"
	"mssgserver/net"
	"mssgserver/server/common"
	"mssgserver/server/game/model"
	"mssgserver/server/game/model/data"
	"sync"
)

// 玩家属性
var RoleAttributeService = &roleAttributeService{
	attrs: map[int]*data.RoleAttribute{},
}

type roleAttributeService struct {
	mutex sync.RWMutex
	attrs map[int]*data.RoleAttribute
}

func (ra *roleAttributeService) TryCreate(rid int, req *net.WsMsgReq) error {
	rr := &data.RoleAttribute{}
	ok, err := db.Engine.Table(rr).Where("rid=?", rid).Get(rr)
	if err != nil {
		log.Println("玩家属性查询出错", err)
		return err
	}
	if !ok {
		//查询不到 则进行初始化的创建
		rr.RId = rid
		rr.ParentId = 0
		rr.UnionId = 0
		rr.PosTags = ""
		_, err := db.Engine.Table(rr).Insert(rr)
		if err != nil {
			log.Println("玩家属性插入出错", err)
			return err
		}
	} else {
		//将属性加入缓存
		//todo
	}

	return nil
}

/*
*
查询属性中的posTag
*/
func (ra *roleAttributeService) GetPosTags(rid int) ([]model.PosTag, error) {
	rr, ok := ra.attrs[rid]
	if !ok {
		//缓存中不存在
		rr = &data.RoleAttribute{}
		_, err := db.Engine.Table(rr).Where("rid=?", rid).Get(rr)
		if err != nil {
			log.Println("GetPosTags查询数据库报错")
			return nil, common.New(constant.DBError, "GetPosTags查询数据库报错")
		}
	}
	tags := rr.PosTags
	posTags := make([]model.PosTag, 0)
	err := json.Unmarshal([]byte(tags), &posTags)
	if err != nil {
		log.Println("posTags解析成json报错")
		return nil, common.New(constant.DBError, "posTags解析成json报错")
	}
	return posTags, nil
}
